import { Component, Input, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DrawerService, TableWidthConfig } from 'ng-devui';
import { map } from 'rxjs';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';

@Component({
  selector: 'app-select-order',
  templateUrl: './select-order.component.html',
  styleUrls: ['./select-order.component.scss']
})
export class SelectOrderComponent {
  @Input() data: any;
  tableheight = '400px';
  creatTime: any = []
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  pageSizeOptions = [10, 20, 30, 50, 100];
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '单据单号',
        fieldType: 'text',
        fixedLeft: '80px'
      },
      {
        field: '客户名称',
        header: '客户名称',
      },
      {
        field: '物料编码',
        header: '物料编码',
        fieldType: 'text'
      },
      {
        field: '物料名称',
        header: '物料名称',
        fieldType: 'text'
      },
      {
        field: '物料规格',
        header: '物料规格',
        fieldType: 'text'
      },
      {
        field: '物料单位',
        header: '物料单位',
        fieldType: 'text'
      },
      {
        field: '数量',
        header: '数量',
        fieldType: 'text'
      },
      {
        field: '已发数量',
        header: '已发数量',
        fieldType: 'text'
      },
      {
        field: '未发数量',
        header: '未发数量',
        fieldType: 'text'
      },
      {
        field: '生产数量',
        header: '生产数量',
        fieldType: 'text'
      },
      {
        field: '单价（含税）',
        header: '单价（含税）',
        fieldType: 'text'
      },
      {
        field: '含税价格',
        header: '含税价格',
        fieldType: 'text'
      },
      {
        field: '税额',
        header: '税额',
        fieldType: 'text'
      },
      {
        field: '折扣（%）',
        header: '折扣（%）',
        fieldType: 'text'
      },
      {
        field: '折扣单价（含税）',
        header: '折扣单价（含税）',
        fieldType: 'text'
      },
      {
        field: '折扣含税金额',
        header: '折扣含税金额',
        fieldType: 'text'
      },
      {
        field: '折扣税额',
        header: '折扣税额',
        fieldType: 'text'
      }
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field: '单据单号',
      width: '200px'
    },
    {
      field: '客户名称',
      width: '200px'
    },
    {
      field: '物料编码',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '物料规格',
      width: '150px'
    },
    {
      field: '物料单位',
      width: '150px'
    },
    {
      field: '数量',
      width: '150px'
    },
    {
      field: '已发数量',
      width: '150px'
    },
    {
      field: '未发数量',
      width: '150px'
    },
    {
      field: '生产数量',
      width: '150px'
    },
    {
      field: '单价（含税）',
      width: '150px'
    },
    {
      field: '含税价格',
      width: '150px'
    },
    {
      field: '税额',
      width: '150px'
    },
    {
      field: '折扣（%）',
      width: '150px'
    },
    {
      field: '折扣单价（含税）',
      width: '150px'
    },
    {
      field: '折扣含税金额',
      width: '150px'
    },
    {
      field: '折扣税额',
      width: '150px'
    }
  ];//表格宽度配置
  Customer: any = []
  fifter = {
    ids: [],
    ZhuanHuanWanGongDanDe: true,
    ZhuanHuanWanDe: false,
    PartNum: '',
    PartName: '',
    CustomerName: '',
    StartTime: '',
    EndTime: '',
    SaleOrderNum: '',
    Status:'审核通过',
    PageNumber: 1,
    PageSize: 30
  }
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  tableData: any
  checkedIds: any;
  rowData: any;
  CheckedRows: any=[];
  filterRows: any=[]
  constructor(private SharedMethodService: SharedMethodService, private SalesService: SalesService) {}
  ngOnInit(): void {

    if(this.data =='工单'){
      this.SalesService.GetSaleOrderPartsWithSaleOrder(this.fifter).pipe(
        // 首先，转换整个响应对象
        map((response: any) => {
          // 过滤 items 数组
          const filteredItems = response.items.filter((item: { quantity: number; soldQuantity: number; produceQuantity: number; }) =>
            item.quantity - item.soldQuantity !== 0 && item.quantity - item.produceQuantity > 0
          );
          return {
            items: filteredItems,
            totalCount: response.totalCount
          };
        })
      ).subscribe((data: any) => {
        this.tableData = data.items;
        this.pager.total = data.totalCount;
      });
    }else{
      this.filter()
    }
  }
  filter() {
    if(this.data.customerName){
      this.fifter.CustomerName = this.data.customerName
    }
    const filterIds = this.data.saleOrderPartId;
    this.SalesService.GetSaleOrderPartsWithSaleOrder(this.fifter).subscribe((data: any) => {
      this.tableData = data.items.map((item: any) => {
        if (filterIds.includes(item.saleOrderPartId)) {
          return {
            ...item,
            $checked: true,
            $halfChecked: false,
            };
          }
          return item;
        }
      );
      this.pager.total = data.totalCount;
      this.CheckedRows = this.tableData.filter((item: any) => item.$checked);
    })
  }
  filter2() {
    this.fifter.PageNumber = 1
    this.filter()
  }
  reset() {
    this.fifter = {
      ids: [],
      ZhuanHuanWanGongDanDe: true,
      ZhuanHuanWanDe: false,
      PartNum: '',
      PartName: '',
      CustomerName: this.data.customerName,
      StartTime: '',
      EndTime: '',
      SaleOrderNum: '',
      Status:'审核通过',
      PageNumber: 1,
      PageSize: 20
    }
    this.creatTime = []
    this.filter()
  }
  dateChange() {
    this.fifter.StartTime = this.creatTime[0].toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
    this.fifter.EndTime = this.creatTime[1].toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'saleOrderPartId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
      this.CheckedRows = this.tableData.filter((item: any) => item.$checked);
    });
  } //获取选中行
  getCheckedRowsData() {
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (data: any) => {
          const filterIds = this.data.saleOrderPartId; // 确保这是一个数组
          this.CheckedRows = data;
          this.tableData = this.tableData.map((item: any) => {
            if (filterIds.includes(item.saleOrderPartId)) {
              return {
                ...item,
                $checked: true,
                $halfChecked: false
              };
            }
            return item;
          });
          this.CheckedRows = this.tableData.filter((item: any) => item.$checked);
          this.filterRows = this.CheckedRows.filter((item: any) => !filterIds.includes(item.saleOrderPartId));
      }
    );
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  pageIndexChange($event: any) {
    this.filter()
  }//切换页码
  pageSizeChange($event: any) {
    this.filter()
  }//改变每页显示数量
  radio($event:any,rowitem:any){
    this.rowData = rowitem
  }
  cleared(){
    this.reset()
  }
}
